package com.key.service.impl;

import com.github.pagehelper.PageHelper;
import com.key.common.R;
import com.key.common.dto.BorrowDTO;
import com.key.common.dto.ReturnAssetsDTO;
import com.key.common.dto.ReturnDTO;
import com.key.common.vo.AssetsTVO;
import com.key.entity.*;
import com.key.mapper.*;
import com.key.service.ReturnAssetsService;
import com.key.utils.ExcelExportHelper;
import com.key.utils.OddNumbersUtils;
import com.key.utils.TranException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wen
 * @create 2023-02-20 10:10
 */
@Service
public class ReturnAssetsServiceImpl implements ReturnAssetsService {
    @Autowired
    WithdrawalAssetsMapper withdrawalAssetsMapper;
    @Autowired
    ReceiptAssetsMapper receiptAssetsMapper;
    @Autowired
    AssetsMapper assetsMapper;
    @Autowired
    ReturnAssetsMapper returnAssetsMapper;
    @Autowired
    BorrowAssetsMapper borrowAssetsMapper;

    @Autowired
    ApprovalMapper approvalMapper;

    @Autowired
    IndexMapper indexMapper;

    @Autowired
    IndexAssetsMapper indexAssetsMapper;


    @Override
    @Transactional
    public R creatReturn(ReturnAssetsDTO returnAssetsDTO) {
        R r=new R();
        String returnNumber= OddNumbersUtils.creatON("GH");
        ReturnAssets returnAssets=returnAssetsDTO.getReturnAssets();

        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        String s = String.valueOf(subject.getPrincipal());
        if(s==null||s==""){
            s="张三";
        }


        try{
            //将归还与资产像关联
            returnAssetsMapper.updateReturnAndAssets(returnNumber,returnAssetsDTO.getBorrowNumber());
            returnAssets.setState("发起");
            returnAssets.setReturnNumber(returnNumber);
            returnAssets.setApproveProgress("未审批");
            returnAssets.setHandlers("未实现“creatReturn”");
            int result =returnAssetsMapper.insertReturn(returnAssets);

            //退库审批单添加
            SysUser sysUser= indexMapper.selectUserInfoByUserName(s);
            Company company = indexAssetsMapper.selectAssetsInCompany(sysUser.getUserId());
            Department department = indexAssetsMapper.selectDeptInfoByEpmId(sysUser.getUserId());
            Approval approval = new Approval();
            approval.setState("未审批");
            approval.setApprovalNo(returnNumber);
            approval.setApplicationType("退库");
            approval.setApplicationTime(OddNumbersUtils.getDay());
            approval.setApplicationPerson(s);
            approval.setApplicationCompany(company.getCompanyName());
            approval.setApplicationDepartment(department.getDepartmentName());

            approvalMapper.insertApproval(approval);

            if(result!=0){
                r.setCode(200);
                r.setMsg("提交申请成功");
                return r;
            }else {
                r.setCode(300);
                r.setMsg("生成清单失败");
                return r;
            }
        }catch (Exception e){
            throw new TranException("事务异常");
        }

    }


    @Override
    @Transactional
    public R deleteReturnAssets(String returnNumbers) {
        R r=new R();
        try {
            int i=returnAssetsMapper.deleteReturnAssetsByReturnNumber(returnNumbers);
            int j=returnAssetsMapper.deleteReturnNumberAndAssets(returnNumbers);
            if(i!=0&&j!=0){
                r.setCode(200);
                r.setMsg("删除成功");
            }else {
                r.setCode(300);
                r.setMsg("删除失败");
            }
        }catch (Exception e){
            throw new TranException("事务错误");
        }
        return r;
    }

    @Override
    public R editReturnAssets(ReturnDTO returnDTO) {
        R r=new R();
        int i=returnAssetsMapper.updateReturnAssets(returnDTO);
        if(i!=0){
            r.setCode(200);
            r.setMsg("修改成功！");
        }else {
            r.setCode(300);
            r.setMsg("修改失败！");
        }
        return r;
    }


    @Override
    public R findReturnAssets(ReturnDTO returnDTO) {
        int currentPage=returnDTO.getCurrentPage();
        int pageSize=returnDTO.getPageSize();
        R r=new R();


        //未分页查询，用于count获取
        List<ReturnAssets> returnAssetsList2 = returnAssetsMapper.selectReturn(returnDTO);
        PageHelper.startPage(currentPage,pageSize);
        List<ReturnAssets> returnAssetsList = returnAssetsMapper.selectReturn(returnDTO);
        if(returnAssetsList!=null){
            r.setCode(200);
            r.setCount(returnAssetsList2.size());
            r.setMsg("success");
            r.setData(returnAssetsList);
        }else {
            r.setCode(400);
            r.setMsg("查询失败！");
        }
        return r;
    }

    @Override
    public List<Assets> findAssetsByReturnAssets(ReturnAssets returnAssets) {
        List<Assets> resultList=returnAssetsMapper.selectAssetsByReturnAssets(returnAssets.getReturnNumber());
        return resultList;
    }

    @Override
    public List<AssetsTVO> findAssetsTVOByReturnAssets(ReturnAssets returnAssets) {
        List<AssetsTVO> resultList=returnAssetsMapper.selectAssetsTVOByReturnAssets(returnAssets.getReturnNumber());
        return resultList;
    }

    @Override
    public HSSFWorkbook getWorkBook() {
        String[] header = {"主键ID", "办理状态", "归还单号", "借用人", "归还后区域", "归还后存放点", "借用日期", "预计归还时间", "实际归还时间",
                "归还备注", "处理人", "审批进度"};
        String[] properties = {"returnId", "state", "returnNumber", "borrower", "returnRegion", "returnStoragePoint", "borrowDate",
                "estimatedReturnTime", "actualReturnTime","returnRemarks",  "handlers", "approveProgress"};

        List<ReturnAssets> returnAssetsList=returnAssetsMapper.selectReturn(new ReturnDTO());

        List list = new ArrayList();
        for (ReturnAssets returnAssets : returnAssetsList) {
            list.add(returnAssets);
        }

        ExcelExportHelper excelHelper = new ExcelExportHelper();
        HSSFWorkbook workbook = excelHelper.exportExcel(header, properties, list, "归还申请单表");
        return workbook;
    }


}
